package pl.puntin.punclient.view.game;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public final class DrawPadComponent extends JPanel
{

	private static final int IMAGE_WIDHT = 640;
	private static final int IMAGE_HEIGHT = 480;
	
	private BufferedImage bufferedImage;
	private Graphics2D graphics2D;
	private int currentX, currentY, oldX, oldY;
	private final motionA motionListener;
	private final mouseA mouseAdapter;
	
	public DrawPadComponent()
	{
		clear();

		
		setPreferredSize(new Dimension(IMAGE_WIDHT, IMAGE_HEIGHT));
		mouseAdapter = new mouseA();
		motionListener = new motionA();
	}
	
	@Override
	protected void paintComponent(final Graphics graphics)
	{
		graphics.drawImage(bufferedImage, 0, 0, null);
	}

	public BufferedImage getBufferedImage()
	{
		return bufferedImage;
	}
	
	public void setBufferedImage(final BufferedImage bufferedImage)
	{
		this.bufferedImage = bufferedImage;
	}

	public void clear() {
		bufferedImage = new BufferedImage(IMAGE_WIDHT, IMAGE_HEIGHT, BufferedImage.TYPE_BYTE_BINARY);
		graphics2D = bufferedImage.createGraphics();
		notLonger();
		whitePencil();
	}
	
	public void youAreDrower()
	{
		addMouseListener(mouseAdapter);
		addMouseMotionListener(motionListener);
	
	}
	
	public void notLonger()
	{
		this.removeMouseListener(mouseAdapter);
		this.removeMouseMotionListener(motionListener);
	}
	
	private class mouseA extends MouseAdapter
	{
		@Override
		public void mousePressed(final MouseEvent e)
		{
			oldX = e.getX();
			oldY = e.getY();
		}
	}
	
	private class motionA extends MouseMotionAdapter
	{
		@Override
		public void mouseDragged(final MouseEvent e)
		{
			currentX = e.getX();
			currentY = e.getY();
			if (graphics2D != null)
				graphics2D.drawLine(oldX, oldY, currentX, currentY);
			
			repaint();
			
			oldX = currentX;
			oldY = currentY;
		}
	}
	
	public void blackPencil()
	{
		graphics2D.setStroke(new BasicStroke(10));
		graphics2D.setColor(Color.BLACK);	
	}
	
	public void whitePencil()
	{
		
		graphics2D.setStroke(new BasicStroke(4));
		graphics2D.setColor(Color.WHITE);
	}
	
}
